package com.mylogistics.controller;


import com.mylogistics.pojo.User;
import com.mylogistics.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * 用户类接口
 */
@RestController
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class UserController {

    @Autowired
    UserService userService;

    @ApiOperation(value = "获取用户的信息")
    @PreAuthorize("hasRole('user')")
    @GetMapping
    public String get() {
        return "获取用户的信息";
    }


    @ApiOperation(value = "新增用户", notes = "假注册")
    @PreAuthorize("hasRole('admin')")
    @PostMapping
    public String add(@Valid User user) {
        return "新增成功";
    }


    @GetMapping("info")
    @ApiOperation(value = "用于展示用户名")
    public User info() {
        //从secruity的holder中获取用户状态
        UserDetails userLogin = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = new User();
        user.setUsername(userLogin.getUsername());
        return user;
    }

    @ApiOperation(value = "登录操作", notes = "security的登录")
    @PostMapping("/login.action")
    public void login2(String username, String password) {
    }

    @PostMapping("/register")
    @ApiOperation(value = "用于注册", notes = "真注册")
    public String register(String username, String password) {
        userService.register(username, password);
        return "注册成功";
    }

    @ApiOperation(value = "根据用户名获取用户资料", notes = "ehcache的实验")
    @PostMapping("/getUser")
    public User getUser(String username) {
        return userService.getUserByUsername(username);
    }

    @ApiOperation(value = "删除用户", notes = "ehcache的实验")
    @PostMapping("/del")
    public void del(String username) {
        userService.delUser(username);
    }

    @ApiOperation(value = "更新用户信息", notes = "ehcache的实验")
    @PostMapping("/edit")
    public void edit(User user) {
        userService.edit(user);
    }

}


